
# this script generate from dbc to json, the format looks like this:
#  {
#     "dbc_name": "xxx.dbc",
#     "can_node_list": [
#         {
#             "node_name": "xxx",
#             "messages": [
#                 {
#                     "can_id": "xxx",
#                     "signals": [
#                         {
#                             "signal_name": "xxx",
#                             "signal_type": "xxx",
#                             "endian": "xxx",
#                             "start_bit": 0,
#                             "len": 0,
#                             "factor": 0,
#                             "offset": 0,
#                             "max": 0,
#                             "min": 0
#                         }
#                     ]
#                 }
#             ]
#         }
#     ]
# }

import json

def gen_can_json(dp, logging):
    can_json = {
        "can_node_list": []
    }
    
    for node in dp.config.can_node_list:
        node_data = {
            "node_name": node['node_name'],
            "messages": []
        }
        
        for message in dp.data:
            if message.can_node == node['node_name']:
                message_data = {
                    "can_id": hex(int(message.id)),
                    "message_name":message.name,
                    "signals": []
                }
                
                for signal in message.signals:
                    signal_data = {
                        "signal_name": signal.name,
                        "signal_type": signal.signal_type,
                        "endian": signal.endian == "BIG_ENDIAN",
                        "start_bit": int(signal.start_bit),
                        "len": int(signal.len),
                        "factor": float(signal.factor),
                        "offset": float(signal.offset),
                        "max": float(signal.max),
                        "min": float(signal.min)
                    }
                    
                    message_data["signals"].append(signal_data)
                
                node_data["messages"].append(message_data)
        
        can_json["can_node_list"].append(node_data)
    
    with open("./output/can.json", "w") as f:
        json.dump(can_json, f, indent=4)
